package myLearnjdk.redis.jedisPool;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Response;

/**
 * 自定义redis连接池的工厂类
 * @author yangcheng  
 * @date 2019年6月24日  
 * @version V1.0
 */
public class MyJedisPoolFactory {
	
	private final GenericObjectPoolConfig poolConfig;
	
	public MyJedisPoolFactory(int maxActive, int maxIdle, long maxWait,
			boolean testOnBorrow, boolean testOnReturn) {
		poolConfig = new GenericObjectPoolConfig();
		poolConfig.setMaxTotal(maxActive);
		poolConfig.setMaxIdle(maxIdle);
		poolConfig.setMaxWaitMillis(maxWait);
		poolConfig.setTestOnBorrow(testOnBorrow);
		poolConfig.setTestOnReturn(testOnReturn);
	}
	
	public JedisPool getJedisClient(String ipPort) {
		return new MyJedisPool(poolConfig, ipPort.split("\\:")[0], Integer.parseInt(ipPort.split("\\:")[1]));
	}
	
	
	public static void main(String[] args) {
		/**
		 * 通过自己创建的连接池工程创建redis连接池
		 */
		JedisPool jedisPool=new MyJedisPoolFactory(10,10,10,true,true).getJedisClient("192.168.18.27:6379");
		/**
		 * 从连接池中获取连接
		 */
		Jedis jedis = null;
		for(int i = 0 ;i < 8 ; i++){
			jedis = jedisPool.getResource();	
		}
		System.out.println("连接池中连接数"+jedisPool.getNumActive());
		System.out.println("连接池中空闲的连接="+jedisPool.getNumIdle());
		/**
		 * 使用连接池中获取出来的连接做操作
		 */
		Pipeline pipeline = jedis.pipelined();
		Response<String>  result = pipeline.get("RET$::1:1234562223:4");
		pipeline.sync();
		/**
		 * Please close pipeline or multi block before calling this method.
		 * 当在获取pipeline返回结果之前，需要先关闭pipeline
		 */
		String str = result.get();
		System.out.println(str);
		/**
		 * 销毁连接池中的所有连接
		 */
		jedisPool.destroy();
		System.out.println("连接池中连接数"+jedisPool.getNumActive());//返回-1
		
	}
}
